<?php
/**
 * Created by PhpStorm.
 * User: another
 * Date: 2019-04-28
 * Time: 10:40
 */
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ServiceProject;
use Illuminate\Http\Request;

class ServiceController extends Controller
{
    protected $serviceModel;

    public function __construct()
    {
        $this->serviceModel = new ServiceProject();
    }

    public function list(Request $request)
    {
        if(!$request->has('page_size'))
            return response()->json(['code'=>'0','message'=>'请上传页面条数']);


        $data = $request->input();
        $list = $this->serviceModel->getServiceProjectList($data);
        return response()->json(['code'=>'1','message'=>'获取成功','data'=>$list]);
    }

    public function addProject(Request $request)
    {
        $data = $request->input();

        $bool_data = $this->getValidator($data);

        if($bool_data['code'] == 0){
            $result['code'] = '0';
            $result['message'] = $bool_data['message'];
            return response()->json($result);
        }

        $bool = $this->serviceModel->addProject($data);
        return response()->json($bool);
    }

    public function updProject(Request $request)
    {
        $data = $request->input();
        if(empty($data['id'])){
            return response()->json(['code'=>'0','message'=>'请选择项目']);
        }

        $bool_data = $this->getValidator($data);

        if($bool_data['code'] == 0){
            $result['code'] = '0';
            $result['message'] = $bool_data['message'];
            return response()->json($result);
        }

        $bool = $this->serviceModel->updProject($data);
        return response()->json($bool);
    }

    public function delect(Request $request)
    {
        $data = $request->input();
        if(empty($data['id'])){
            return response()->json(['code'=>'0','message'=>'请选择项目']);
        }

        $bool = $this->serviceModel->getDelect($data['id']);
        return response()->json($bool);
    }

    /**
     * 验证
     * @param $data
     * @return array
     */
    public function getValidator($data)
    {
        $validator = \Validator::make($data,[
            'title'=>'required|max:50',
            'describe'=>'required',
        ],[
            'required'=>':attribute为必填项',
            'max'=>':attribute长度不符合要求',
        ],[
            'title'=>'项目名称',
            'describe'=>'项目描述',
        ]);


        //验证失败，并返回第一个报错
        if($validator->fails()) {
            return ['code' => 0, 'message' => $validator->errors()->first()];
        }

        return ['code'=>1,'message'=>'验证成功'];
    }
}
